/*!
 * Grid component 
 */
(function(){
	this.Grid= Component.extend({
		init:function(opts){
			this._super(opts);
			this._create();
		},
		defaultopts:{
			height:400,
			width:'auto'
		},
		_create:function(){
			var grid= this;
			this.$e.height(this.opts.height).width(this.opts.width);
			this.$e.addClass("vcolgridcontainer");
			$.template("vcolgridframe",'<div class="gridheader"><div class="gridheaderinner"><table cellpadding="0" cellspacing="0"><thead><tr>{{each columns}}<th scope="col" field="${$value.field}" findex="${$index}"><div>${$value.header}</div></th>{{/each}}</tr></thead></table></div></div><div class="gridbody"><table cellpadding="0" cellspacing="0"><tbody id="${id}-tbody"></tbody></table></div>');
			$.tmpl( "vcolgridframe", this.opts ).appendTo( "#"+this.opts.id );
			//bind events
			$( "#"+this.opts.id +"-tbody").delegate("tr","click", function(e){
				var $row  = $(this),ti= $.tmplItem(this),griddata=ti.data,rindex=$row.attr("rindex"),row=griddata.rows[rindex],$rows=ti.nodes;
				grid.fireEvent("rowclick",{rowdata:row,rowindex:rindex,row:$row},e,function(e,data){
					$( "#"+this.opts.id +"-tbody .selected").removeClass("selected");
					data.row.addClass("selected");
				});
			});
			this.size();
		},
		size:function(){
			this._super();
			var headerHeight= $(".gridheader",this.$e).outerHeight(),grid=this;
			$(".gridbody").height(this.$e.height()-headerHeight );
			//remember the column header width & set the body columns width
			$("th",this.$e).each(function(){
				var w = $(this).width(),findex = this.getAttribute("findex");
				grid.opts.columns[findex].width=w;
				$("td[findex="+findex+"]").width(w);
			});
		},
		loadData:function(data){
			//fill data
			$.template("vcolgriddatarows",'{{each(ri,r) rows}}<tr rindex="${ri}"  class="${ri%2==1?"even":"odd"}">{{each $item.columns}}<td style="width:${$value.width}px" findex="${$index}" ><div>${$item.data.rows[$index][$value.field]}</div></td>{{/each}}</tr>{{/each}}');
			var $tbody = $("tbody",this.$e).html("");
			var $rows= $.tmpl( "vcolgriddatarows",data,this.opts).appendTo( "#"+this.opts.id +"-tbody");
		}
		
	});
})();